import axios, { AxiosRequestConfig, AxiosResponse, RawAxiosRequestHeaders } from 'axios'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useLogin } from '@/pinia'
import { useRouter } from 'vue-router'
export interface Response {
    code: string
    msg: string
    data: any
}
const request = axios.create({
    // baseURL: import.meta.env.VITE_BASEURL,
    timeout: 10000,
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    }
})
const writeUrlList = [
    "https://devapi.qweather.com/v7/weather/3d?location=101110101&key=4d3239b0e0f64cec8e21fbdba90e28d2",
    "/src/assets/city.json"
]
// 请求拦截
request.interceptors.request.use(
    (config: AxiosRequestConfig<any>) => {
        // 不校验外部接口
        if (config.url && writeUrlList.includes(config.url)) return config       

        const LoginStore = useLogin()
        if (LoginStore.token) {
            // 统一设置用户身份 Token
            (config.headers as RawAxiosRequestHeaders).Authorization = LoginStore.token
        }
        // 对传递图片文件的接口修改请求头
        if (config.url === "/api/system/user" && ["post", "put"].includes(config.method!)) {
            config.headers!["Content-Type"] = "application/multipart/form-data"
        } else {
            config.headers!["Content-Type"] = "application/json;charset=utf-8"
        }

        return config
    },
    (error) => {
        return Promise.reject(error)
    })

// 响应拦截
request.interceptors.response.use(
    (response: AxiosResponse<Response, any>): AxiosResponse<Response, any> => {
        const { config } = response
        // 不校验外部接口
        if (config.url && writeUrlList.includes(config.url)) return response

        const LoginStore = useLogin()
        LoginStore.$patch({
            // 获取后端传递的最新的token
            token: response.headers["authorization"]
        })

        // 判断是否存在token
        if (!config.headers?.Authorization) {

            if (config.url === "/api/login") {
                return response
            }
            response.data = {
                code: "401",
                msg: "登录过期",
                data: null
            }
            ElMessageBox.confirm(
                '登录状态过期，请重新登录',
                'Warning',
                {
                    confirmButtonText: '返回登录',
                    type: 'warning',
                }
            ).then(() => {
                const router = useRouter()
                router.push("/login")
            })
            return response
        }
        return response

    }, (error) => {
        // 监听错误
        if (error.code === "ECONNABORTED") {
            ElNotification({
                title: error.name,
                message: "请求超时!",
                type: 'error',
            })
        } else {
            ElNotification({
                title: error.name,
                message: error.message,
                type: 'error',
            })
        }

        return false
    }
)

export default request